<template>
  <div class="grade-page">
    <h2>评分：{{ paper?.title || '加载中...' }}</h2>
    <el-form :model="gradingForm" ref="gradeFormRef" label-width="0">
      <el-card v-for="(item, index) in gradingData" :key="item.question.id" class="question-card">
        <template #header>
          <div class="question-header">
            <span>{{ index + 1 }}. {{ item.question.title }} ({{ typeMap[item.question.type] }})</span>
          </div>
        </template>
        <div class="question-content">{{ item.question.content }}</div>
        <div class="answer-info">
          <p><strong>学生答案：</strong>{{ item.answer || '未作答' }}</p>
          <p><strong>正确答案：</strong>{{ item.question.answer }}</p>
          <p v-if="item.question.type === 'SINGLE_CHOICE'"><strong>选项：</strong>{{ item.question.options }}</p>
        </div>
        <el-form-item
          :prop="`scores.${item.question.id}`"
          :rules="[{ required: true, message: '请输入分数', trigger: 'blur' }]"
          v-if="item.question.type === 'TEXT'"
        >
          <el-input
            v-model="gradingForm.scores[item.question.id]"
            placeholder="请输入分数"
            type="number"
          ></el-input>
        </el-form-item>
        <div v-else>
          <p><strong>自动评分：</strong>{{ item.autoScore ?? '待评分' }}</p>
        </div>
      </el-card>
      <el-form-item>
        <el-button type="primary" @click="submitGrading" :loading="submitting">提交评分</el-button>
        <el-button @click="$router.go(-1)">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { usePaperStore } from '@/stores/api/paper';
import { usePaperSubmissionStore } from '@/stores/api/paper-submission';
import { useQuestionStore } from '@/stores/api/question';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';

const route = useRoute();
const router = useRouter();
const paperStore = usePaperStore();
const paperSubmissionStore = usePaperSubmissionStore();
const questionStore = useQuestionStore();

const typeMap = {
  SINGLE_CHOICE: '单选题',
  TRUE_FALSE: '判断题',
  TEXT: '大题',
};

const submission = ref(null);
const paper = ref(null);
const gradingData = ref([]);
const gradingForm = ref({ scores: {} });
const submitting = ref(false);
const gradeFormRef = ref<FormInstance>();

const formRules = ref<FormRules>({
  scores: {
    type: 'object',
    fields: {},
  },
});

interface PaperSubmission {
  id: number;
  paperId: number;
  studentId: number;
  answers: { [key: string]: string };
  submissionTime: string;
  submissionStatus: 'SUBMITTED' | 'GRADED';
  score: number | null;
}

const fetchSubmissionData = async () => {
  const submissionId = parseInt(route.params.submissionId as string);
  try {
    submission.value = await paperSubmissionStore.fetchSubmissionById(submissionId);
    paper.value = await paperStore.fetchPaperById(submission.value.paperId);
    const questionPromises = paper.value.questionIds.map((id: number) => questionStore.fetchQuestionById(id));
    const questions = await Promise.all(questionPromises);
    gradingData.value = questions.map((q: any) => {
      const answer = submission.value?.answers[q.id.toString()];
      const autoScore = q.type !== 'TEXT' ? (answer === q.answer ? 10 : 0) : null;
      return { question: q, answer, autoScore };
    });
    gradingData.value.forEach(item => {
      if (item.question.type === 'TEXT') {
        gradingForm.value.scores[item.question.id] = '';
        formRules.value.scores.fields[item.question.id] = [
          { required: true, message: '请输入分数', trigger: 'blur' },
          { type: 'number', min: 0, message: '分数需为非负数', trigger: 'blur' },
        ];
      }
    });
  } catch (error) {
    ElMessage.error('加载评分数据失败: ' + error);
    console.error('Error fetching submission data:', error);
  }
};

const submitGrading = async () => {
  if (!gradeFormRef.value) return;
  gradeFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;
      try {
        const textQuestionScores: { [key: string]: string } = {};
        gradingData.value.forEach(item => {
          if (item.question.type === 'TEXT') {
            textQuestionScores[item.question.id] = gradingForm.value.scores[item.question.id].toString();
          }
        });
        const gradingRequest = {
          submissionId: submission.value!.id,
          textQuestionScores,
        };
        await paperSubmissionStore.gradeSubmission(gradingRequest);
        router.push('/exam/grade');
      } catch (error) {
        ElMessage.error('评分提交失败');
      } finally {
        submitting.value = false;
      }
    }
  });
};

onMounted(() => {
  fetchSubmissionData();
});
</script>

<style scoped>
.grade-page {
  width: 80%;
  margin: 40px auto;
}

h2 {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 20px;
}

.question-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.question-header {
  font-size: 16px;
  color: #333;
}

.question-content {
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.answer-info p {
  margin: 5px 0;
  font-size: 14px;
}

.el-input {
  width: 100px;
}

.el-button {
  margin-right: 10px;
}
</style>